package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioConstantProperties minioConstantProperties;
    /**
     * @author gengjian
     * @date 2025/02/18 18:48:18
     * 文件上传返回文件访问地址
     * 文件上传需要考虑的事情
     * 文件大小
     * 文件格式
     * 文件名称
     * 存储位置
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //创建minio客户端连接对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConstantProperties.getEndpointUrl())
                    .credentials(minioConstantProperties.getAccessKey(),minioConstantProperties.getSecreKey())
                    .build();
            //判断桶是否存在
            String bucketName = minioConstantProperties.getBucketName();
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());

            if (!found){
                //如果桶不存在则创建
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }else {
                //如果桶存在则直接上传
                System.out.println("Bucket" + bucketName + "already exists");
            }
            //上传文件 文件名：随机uuid+.后缀名 原始文件名截取从.到最后
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replaceAll("-","")
                    + originalFilename.substring(originalFilename.lastIndexOf("."));
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            //返回数据，访问文件的全路径 ip地址+文件存储位置+文件名
            String url = minioConstantProperties.getEndpointUrl() + "/" + bucketName + "/" + fileName;
            return url;
        } catch (ErrorResponseException e) {
            throw new RuntimeException(e);
        } catch (InsufficientDataException e) {
            throw new RuntimeException(e);
        } catch (InternalException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (InvalidResponseException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        } catch (XmlParserException e) {
            throw new RuntimeException(e);
        }
    }
}
